package com.iwhalecloud.bss.kite.cucc.service.attr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.hsf.baseinf.service.InfExchangeService;
import com.iwhalecloud.bss.kite.cart.common.util.KiteCartBeanUtils;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.IInstallationAddressService;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.IUnicomRegionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.*;
import com.iwhalecloud.bss.kite.cucc.client.vo.attr.BuildingInfo;
import com.iwhalecloud.bss.kite.cucc.client.vo.attr.BuildingInfoVo;
import com.iwhalecloud.bss.kite.cucc.client.vo.attr.CircuitResourceInfoVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.attr.MappingAttrVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.attr.MappingGoodsVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.attr.MappingProductVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.attr.StandardAddressVO;
import com.iwhalecloud.bss.kite.cucc.common.callclient.HttpsCallClient;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalCallClientEnum;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalErrorConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.CommonUtil;
import com.iwhalecloud.bss.kite.cucc.common.util.KiteAssert;
import com.iwhalecloud.bss.kite.cucc.service.inf.InfServiceHelper;
import com.iwhalecloud.bss.kite.cucc.service.util.CallClientUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.LocalTokenUtil;
import com.iwhalecloud.bss.kite.cucc.service.util.PayUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.OfferDetail;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.ztesoft.bss.common.bo.PostInfo;
import com.ztesoft.bss.common.bo.UserInfo;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class InstallationAddressService implements IInstallationAddressService {

    private static final String RES_PREJUDGE_API_OP_CODE = "json_middlleplatform_resourcePrejudge_resourcePrejudge";
    private static final String ATTR_MAPPING_API_OP_CODE = "json_chinaUnicom_govEnterprise_orderCenter_attrsMappingService";

    @Value("${interface.call.mode:hsf}")
    private String mode;

    @Resource
    private IQuerySceneInstService querySceneInstService;

    @Resource
    private IUnicomRegionService unicomRegionService;

    /**
     * 标准地址查询（接口文档页码（pageNum）从0开始）
     * @author zhang.song
     * @date 2021-02-24 17:19
     * @param stdAddrQryDTO
     * @return com.iwhalecloud.bss.kite.local.client.api.vo.StandardAddressVO
     */
    @Override
    public StandardAddressVO queryStandardAddress(StdAddrQryDTO stdAddrQryDTO) {
        InstallationAddressDTO installationAddressDTO = this.stdAddrQryDTOToInstallationAddressDTO(stdAddrQryDTO);
        Integer pageNum = stdAddrQryDTO.getPageNum() == null ? 1 : Integer.parseInt(stdAddrQryDTO.getPageNum());
        Integer pageSize = stdAddrQryDTO.getPageSize() == null ? 10 : Integer.parseInt(stdAddrQryDTO.getPageSize());
        installationAddressDTO.setPageNum(pageNum-1);
        installationAddressDTO.setPageSize(pageSize);
        installationAddressDTO.setDisplayRelBuildInfo("1");
        installationAddressDTO.setSegmType(stdAddrQryDTO.getSegmType());
        Map<String, Object> requestMap = new HashMap<>();
        Map uniBssBody = new HashMap();
        // 这里统一使用 JTTY-集团统一
        installationAddressDTO.setProvinceRoute("JTTY");
        uniBssBody.put("STANDARD_ADDRESS_REQ", installationAddressDTO);
        requestMap.put("UNI_BSS_BODY", uniBssBody);
        requestMap.put("OP_CODE", "json_middlleplatform_pstandardAddress_standardAddress");
        InfServiceHelper.adaptGray(requestMap, requestMap);
        String respStr =null;
        try {
            if (KiteStringUtils.isEqual(mode, "http")) {
                respStr = HttpsCallClient.postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, requestMap, LocalTokenUtil.getHeaderMap());
            } else {
                InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
                respStr = infExchangeService.exchange(new JSONObject(requestMap));
            }
        } catch (Exception e) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("装机地址接口异常，请核实接口服务是否可用[json_middlleplatform_pstandardAddress_standardAddress]");

        }

        StandardAddressVO standardAddressVo = new StandardAddressVO();
        Map respMap = JSON.parseObject(respStr, Map.class);
        Map headMap = MapUtils.getMap(respMap, "UNI_BSS_HEAD");
        if(!"00000".equals(MapUtils.getString(headMap, "RESP_CODE"))) {
            standardAddressVo.setCode(MapUtils.getString(headMap, "RESP_CODE"));
            standardAddressVo.setMessage(MapUtils.getString(headMap, "RESP_DESC"));
            return standardAddressVo;
        }

        Map respBody = MapUtils.getMap(respMap, "UNI_BSS_BODY");
        Map standardAddressRsp = MapUtils.getMap(respBody, "STANDARD_ADDRESS_RSP");

        Map netHeadMap = MapUtils.getMap(standardAddressRsp, "UNI_NET_HEAD");
        if(!"0000".equals(MapUtils.getString(netHeadMap, "RESP_CODE"))) {
            standardAddressVo.setCode(MapUtils.getString(netHeadMap, "RESP_CODE"));
            standardAddressVo.setMessage(MapUtils.getString(netHeadMap, "RESP_DESC"));
            return standardAddressVo;
        }

        Map dataBody = CommonUtil.getMap(standardAddressRsp, "UNI_NET_BODY");
        if(!"200".equals(MapUtils.getString(dataBody, "code"))) {
            standardAddressVo.setCode(MapUtils.getString(dataBody, "code"));
            standardAddressVo.setMessage(MapUtils.getString(dataBody, "message"));
            return standardAddressVo;
        }

        Integer count = MapUtils.getInteger(dataBody, "count");
        List<StandardAddressDTO> list = CommonUtil.getList(dataBody, "data");

        standardAddressVo.setCount(count);
        standardAddressVo.setPageSize(pageSize);
        standardAddressVo.setPageNum(pageNum);
        standardAddressVo.setPageCount((count == null || count == 0)?0:((count - 1) / pageSize + 1));
        standardAddressVo.setStandardAddressList(list);
        standardAddressVo.setCode("00000");
        return standardAddressVo;
    }

    /**
     * 双线资源核查接口数据接口
     * @author zhang.song
     * @date 2021-02-26 17:15
     * @param pduCirResDTO
     * @return com.iwhalecloud.bss.kite.local.client.api.vo.CircuitResourceInfoVO
     */
    @Override
    public CircuitResourceInfoVO duCirResCheck(PduCirResDTO pduCirResDTO) {
        Map<String, Object> requestMap = this.getContentMap(pduCirResDTO);
        InfServiceHelper.adaptGray(requestMap, requestMap);
        String respStr;
        if (KiteStringUtils.isEqual(mode, "http")) {
            respStr = HttpsCallClient.postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, requestMap, LocalTokenUtil.getHeaderMap());
        } else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            respStr = infExchangeService.exchange(new JSONObject(requestMap));
        }

        CircuitResourceInfoVO circuitResourceInfoVO = new CircuitResourceInfoVO();
        Map respMap = JSON.parseObject(respStr, Map.class);
        Map headMap = MapUtils.getMap(respMap, "UNI_BSS_HEAD");
        if(!"00000".equals(MapUtils.getString(headMap, "RESP_CODE"))) {
            circuitResourceInfoVO.setCode(MapUtils.getString(headMap, "RESP_CODE"));
            circuitResourceInfoVO.setMessage(MapUtils.getString(headMap, "RESP_DESC"));
            return circuitResourceInfoVO;
        }

        Map respBody = MapUtils.getMap(respMap, "UNI_BSS_BODY");
        Map duCirResCheckRsp = MapUtils.getMap(respBody, "DU_CIR_RES_CHECK_RSP");

        Map netHeadMap = MapUtils.getMap(duCirResCheckRsp, "UNI_NET_HEAD");
        if(!"0000".equals(MapUtils.getString(netHeadMap, "RESP_CODE"))) {
            circuitResourceInfoVO.setCode(MapUtils.getString(netHeadMap, "RESP_CODE"));
            circuitResourceInfoVO.setMessage(MapUtils.getString(netHeadMap, "RESP_DESC"));
            return circuitResourceInfoVO;
        }

        Map dataBody = CommonUtil.getMap(duCirResCheckRsp, "UNI_NET_BODY");
        if(!"200".equals(MapUtils.getString(dataBody, "CODE"))) {
            circuitResourceInfoVO.setCode(MapUtils.getString(dataBody, "CODE"));
            circuitResourceInfoVO.setMessage(MapUtils.getString(dataBody, "MESS"));
            return circuitResourceInfoVO;
        }

        Map dualCirResCheckRsp = MapUtils.getMap(dataBody, "DUAL_CIR_RES_CHECK_RSP");
        circuitResourceInfoVO.setChkCode(MapUtils.getInteger(dualCirResCheckRsp, "CHK_CODE"));
        circuitResourceInfoVO.setChkMess(MapUtils.getString(dualCirResCheckRsp, "CHK_MESS"));
        circuitResourceInfoVO.setChkLimitTime(MapUtils.getString(dualCirResCheckRsp, "CHK_LIMIT_TIME"));
        circuitResourceInfoVO.setCirResA(mapToResourceInfoDTO(dualCirResCheckRsp, "DUAL_CIR_RES_CHECK_RSP_A"));
        circuitResourceInfoVO.setCirResZ(mapToResourceInfoDTO(dualCirResCheckRsp, "DUAL_CIR_RES_CHECK_RSP_Z"));
        circuitResourceInfoVO.setCode("00000");
        return circuitResourceInfoVO;
    }

    /**
     * 3.3.楼宇信息查询服务(使用地址ID)
     * @author zhang.song
     * @date 2021-04-13 10:16
     * @param buildingInquiryDTO
     * @return com.iwhalecloud.bss.kite.local.client.api.vo.BuildingInfoVo
     */
    @Override
    public BuildingInfoVo queryBuilding(BuildingInquiryDTO buildingInquiryDTO) {
        Map<String, Object> requestMap = new HashMap<>();
        Map uniBssBody = new HashMap();
        uniBssBody.put("BUILDING_INQUIRY_REQ", buildingInquiryDTO);
        requestMap.put("UNI_BSS_BODY", uniBssBody);
        requestMap.put("OP_CODE", "json_chinaUnicom_networkMidPlatform_abilityGateway_buildingInquiry");
        InfServiceHelper.adaptGray(requestMap, requestMap);
        String respStr;
        if (KiteStringUtils.isEqual(mode, "http")) {
            respStr = HttpsCallClient.postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, requestMap, LocalTokenUtil.getHeaderMap());
        } else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            respStr = infExchangeService.exchange(new JSONObject(requestMap));
        }

        BuildingInfoVo buildingInfoVo = new BuildingInfoVo();
        Map respMap = JSON.parseObject(respStr, Map.class);
        Map headMap = MapUtils.getMap(respMap, "UNI_BSS_HEAD");
        if(!"00000".equals(MapUtils.getString(headMap, "RESP_CODE"))) {
            buildingInfoVo.setCode(MapUtils.getString(headMap, "RESP_CODE"));
            buildingInfoVo.setMessage(MapUtils.getString(headMap, "RESP_DESC"));
            return buildingInfoVo;
        }

        Map respBody = MapUtils.getMap(respMap, "UNI_BSS_BODY");
        Map buildingInquiryRsp = MapUtils.getMap(respBody, "BUILDING_INQUIRY_RSP");
        Map netHeadMap = MapUtils.getMap(buildingInquiryRsp, "UNI_NET_HEAD");
        if(!"0000".equals(MapUtils.getString(netHeadMap, "RESP_CODE"))) {
            buildingInfoVo.setCode(MapUtils.getString(netHeadMap, "RESP_CODE"));
            buildingInfoVo.setMessage(MapUtils.getString(netHeadMap, "RESP_DESC"));
            return buildingInfoVo;
        }

        Map dataBody = CommonUtil.getMap(buildingInquiryRsp, "UNI_NET_BODY");
        if(!"200".equals(MapUtils.getString(dataBody, "code"))) {
            buildingInfoVo.setCode(MapUtils.getString(dataBody, "code"));
            buildingInfoVo.setMessage(MapUtils.getString(dataBody, "message"));
            return buildingInfoVo;
        }

        List<JSONObject> jsonObjectList = CommonUtil.getList(dataBody, "data");
        List<BuildingInfo> buildingInfoList = JSONObject.parseArray(JSONObject.toJSON(jsonObjectList).toString(), BuildingInfo.class);
        buildingInfoVo.setCode("00000");
        buildingInfoVo.setBuildingInfoList(buildingInfoList);
        return buildingInfoVo;
    }

    /**
     * 将装机地址接口入参转为调外系统接口文档规定格式
     */
    private InstallationAddressDTO stdAddrQryDTOToInstallationAddressDTO(StdAddrQryDTO stdAddrQryDTO) {
        String provinceId;
        String cityId;
        String districtId;
        String prodInstId = stdAddrQryDTO.getProdInstId();

        if (KiteStringUtils.isNotEmpty(prodInstId)) {
            String provinceKey;
            String cityKey;
            String districtKey;
            if("2_0000117".equals(stdAddrQryDTO.getFieldName())) {
                // Z端
                provinceKey = "2_0000107";
                cityKey = "2_0000109";
                districtKey = "2_0000111";
            } else {
                // A端
                provinceKey = "2_0000220";
                cityKey = "2_0000221";
                districtKey = "2_0000222";
            }
            String custId = stdAddrQryDTO.getCustId();
            provinceId = querySceneInstService.getProdInstAttrValue(custId, prodInstId, provinceKey);
            cityId = querySceneInstService.getProdInstAttrValue(custId, prodInstId, cityKey);
            districtId = querySceneInstService.getProdInstAttrValue(custId, prodInstId, districtKey);
        } else {
            provinceId = stdAddrQryDTO.getProvinceCode();
            cityId = Optional.ofNullable(stdAddrQryDTO.getEparchyCode()).orElse("");
            districtId = Optional.ofNullable(stdAddrQryDTO.getCityCode()).orElse("");
        }
        KiteAssert.notBlank(provinceId, LocalErrorConsts.PROVINCE_IS_EMPTY);

        AreaInquiry areaInquiry = new AreaInquiry();
        if(KiteStringUtils.isNotEmpty(districtId)) {
            areaInquiry.setGradeId(3);
            areaInquiry.setCode(districtId);
        } else if(KiteStringUtils.isNotEmpty(cityId)) {
            areaInquiry.setGradeId(2);
            areaInquiry.setCode(cityId);
        } else {
            areaInquiry.setGradeId(1);
            areaInquiry.setCode(provinceId);
        }
        InstallationAddressDTO installationAddressDTO = new InstallationAddressDTO();

        // 区域编码转换
        AreaCode areaCode = unicomRegionService.regionTransform(areaInquiry);
        if(areaCode != null && KiteStringUtils.equals(areaCode.getCode(), "00000")) {
            if(KiteStringUtils.isNotEmpty(areaCode.getProvinceCode())) {
                installationAddressDTO.setProvinceId(areaCode.getProvinceCode());
            }
            if(KiteStringUtils.isNotEmpty(areaCode.getCityCode())) {
                installationAddressDTO.setCityId(areaCode.getCityCode());
            }
            if(KiteStringUtils.isNotEmpty(areaCode.getDistrictCode())) {
                installationAddressDTO.setDistrictId(areaCode.getDistrictCode());
            }
        }
        installationAddressDTO.setAddressName(stdAddrQryDTO.getAddrKeyword());
        return installationAddressDTO;
    }

    /**
     * 前端参数拼接成接口入参格式
     */
    private Map<String, Object> getContentMap(PduCirResDTO pduCirResDTO) {
        Map<String, Object> dualCirResCheckReq = new HashMap<>();
        String prodInstId = pduCirResDTO.getProdInstId();
        if (KiteStringUtils.isEmpty(prodInstId)) {
            BssException.throwOut("", "", "场景实例id不能为空");
        }
        String custId = pduCirResDTO.getCustId();
        String provinceA = querySceneInstService.getProdInstAttrValue(custId, prodInstId, "2_0000220");
        if(KiteStringUtils.isEmpty(provinceA)) {
            BssException.throwOut("", "", "A端省份不能为空");
        }
        dualCirResCheckReq.put("PROVINCE_A", provinceA);
        if("2_0000117".equals(pduCirResDTO.getFieldName())) {
            // Z端
            String stdAddressA = querySceneInstService.getProdInstAttrValue(custId, prodInstId, "200003060");
            if(KiteStringUtils.isEmpty(stdAddressA)) {
                BssException.throwOut("", "", "A端标准地址编码不能为空");
            }
            dualCirResCheckReq.put("STD_ADDRESS_A", stdAddressA);
            String provinceZ = querySceneInstService.getProdInstAttrValue(custId, prodInstId, "2_0000107");
            if(KiteStringUtils.isEmpty(provinceZ)) {
                BssException.throwOut("", "", "Z端省份不能为空");
            }
            dualCirResCheckReq.put("PROVINCE_Z", provinceZ);
            dualCirResCheckReq.put("STD_ADDRESS_Z", pduCirResDTO.getStdAddress());
        } else {
            dualCirResCheckReq.put("STD_ADDRESS_A", pduCirResDTO.getStdAddress());
        }

        // 带宽
        String rateKey = "2_0000001";
        KiteAttr rateAttr = querySceneInstService.getProdInstAttr(custId, prodInstId, rateKey);
        if (Objects.nonNull(rateAttr)) {
            String valueDesc = rateAttr.getValueDesc();
            if(KiteStringUtils.isNotEmpty(valueDesc) && valueDesc.length() > 1) {
                pduCirResDTO.setCircuitRate(Float.parseFloat(valueDesc.substring(0, valueDesc.length() - 1)));
                pduCirResDTO.setCircuitRateUnit(valueDesc.substring(valueDesc.length() - 1));
            }
        }
        if(KiteStringUtils.isEmpty(pduCirResDTO.getCircuitRateUnit())) {
            BssException.throwOut("", "", "带宽不能为空");
        }
        dualCirResCheckReq.put("CIRCUIT_TYPE", KiteStringUtils.isEmpty(pduCirResDTO.getCircuitType()) ? "SDH" : pduCirResDTO.getCircuitType());
        dualCirResCheckReq.put("CIRCUIT_RATE", pduCirResDTO.getCircuitRate());
        dualCirResCheckReq.put("CIRCUIT_RATE_UNIT", pduCirResDTO.getCircuitRateUnit());
        if (KiteStringUtils.isNotEmpty(pduCirResDTO.getCoreType())) {
            dualCirResCheckReq.put("CORE_TYPE", pduCirResDTO.getCoreType());
        }
        if (KiteStringUtils.isNotEmpty(pduCirResDTO.getNeedResList())) {
            dualCirResCheckReq.put("NEED_RES_LIST", pduCirResDTO.getNeedResList());
        }

        Map<String, Object> requestMap = new HashMap<>();
        Map<String, Object> uniBssBody = new HashMap();
        Map<String, Object> duCirResCheckReq = new HashMap<>();
        // 这里统一使用 JTTY-集团统一
        duCirResCheckReq.put("provinceRoute", "JTTY");
        // duCirResCheckReq.put("provinceRoute", pduCirResDTO.getProvinceRoute());

        duCirResCheckReq.put("DUAL_CIR_RES_CHECK_REQ", dualCirResCheckReq);
        uniBssBody.put("DU_CIR_RES_CHECK_REQ", duCirResCheckReq);
        requestMap.put("UNI_BSS_BODY", uniBssBody);
        requestMap.put("OP_CODE", "json_middlleplatform_pduCirResCheck_duCirResCheck");
        return requestMap;
    }

    /**
     * 组装返回报文
     */
    private static CircuitResourceInfoDTO mapToResourceInfoDTO(Map dualCirResCheckRsp, String key) {
        CircuitResourceInfoDTO circuitResourceInfoDTO = new CircuitResourceInfoDTO();
        Map dualCirResCheckRspMap = MapUtils.getMap(dualCirResCheckRsp, key);
        if(dualCirResCheckRspMap != null && dualCirResCheckRspMap.size() > 0) {
            circuitResourceInfoDTO.setStdAddress(MapUtils.getString(dualCirResCheckRspMap, "STD_ADDRESS"));
            circuitResourceInfoDTO.setStdAddressFullName(MapUtils.getString(dualCirResCheckRspMap, "STD_ADDRESS_FULLNAME"));
            circuitResourceInfoDTO.setChkCode(MapUtils.getInteger(dualCirResCheckRspMap, "CHK_CODE"));
            circuitResourceInfoDTO.setChkMess(MapUtils.getString(dualCirResCheckRspMap, "CHK_MESS"));
            circuitResourceInfoDTO.setChkLimitTime(MapUtils.getString(dualCirResCheckRspMap, "CHK_LIMIT_TIME"));
            circuitResourceInfoDTO.setChkJumpNum(MapUtils.getString(dualCirResCheckRspMap, "CHK_JUMP_NUM"));
            circuitResourceInfoDTO.setChkOptLength(MapUtils.getString(dualCirResCheckRspMap, "CHK_OPT_LENGTH"));
            circuitResourceInfoDTO.setChkResTxt(MapUtils.getString(dualCirResCheckRspMap, "CHK_RES_TXT"));

            List<Map<String, Object>> chkResList = CommonUtil.getList(dualCirResCheckRspMap, "CHK_RES_LIST");
            if(chkResList != null && chkResList.size() > 0) {
                List<ResourceInfoDTO> resourceInfoList = new ArrayList<>();
                ResourceInfoDTO resourceInfoDTO;
                for (Map<String, Object> chkResMap : chkResList) {
                    resourceInfoDTO = new ResourceInfoDTO();
                    resourceInfoDTO.setRouteSeq(MapUtils.getString(chkResMap, "ROUTE_SEQ"));
                    resourceInfoDTO.setResType(MapUtils.getString(chkResMap, "RES_TYPE"));
                    resourceInfoDTO.setResName(MapUtils.getString(chkResMap, "RES_NAME"));
                    resourceInfoDTO.setWgs84X(MapUtils.getString(chkResMap, "WGS84_X"));
                    resourceInfoDTO.setWgs84Y(MapUtils.getString(chkResMap, "WGS84_Y"));
                    resourceInfoDTO.setLength(MapUtils.getString(chkResMap, "LENGTH"));
                    resourceInfoDTO.setCoreNum(MapUtils.getInteger(chkResMap, "CORE_NUM"));
                    resourceInfoDTO.setCoreFreeNum(MapUtils.getInteger(chkResMap, "CORE_FREE_NUM"));
                    resourceInfoDTO.setTermNum(MapUtils.getInteger(chkResMap, "TERM_NUM"));
                    resourceInfoDTO.setTermFreeNum(MapUtils.getInteger(chkResMap, "TERM_FREE_NUM"));
                    resourceInfoDTO.setPortNum(MapUtils.getInteger(chkResMap, "PORT_NUM"));
                    resourceInfoDTO.setPortMess(MapUtils.getString(chkResMap, "PORT_MESS"));
                    resourceInfoList.add(resourceInfoDTO);
                }
                circuitResourceInfoDTO.setChkResList(resourceInfoList);
            }
        }
        return circuitResourceInfoDTO;
    }

    @Override
    public Object resourPrejudgement(ResPreQryDTO resPreQryDTO) {
        ResPrejudQryDTO resPrejudQryDTO = this.formRequestMessages(resPreQryDTO);
        Map<String, Object> resPrejudQryMap = PayUtil.HumpToLine(resPrejudQryDTO);
        Map<String, Object> uniBssBody = new HashMap();
        uniBssBody.put("RES_PREJUDGE_API_REQ", resPrejudQryMap);
        Map<String, Object> param = new HashMap<>();
        param.put("UNI_BSS_BODY", uniBssBody);
        param.put("OP_CODE", RES_PREJUDGE_API_OP_CODE);
        InfServiceHelper.adaptGray(param, resPrejudQryMap);
        String resultStr =null;
        try {
            if (CallClientUtils.callByHttp()) {
                resultStr = HttpsCallClient.postStringWithObject(LocalCallClientEnum.INF_COMMON_URL.getCenterCode(),
                    LocalCallClientEnum.INF_COMMON_URL.getServiceCode(), param, LocalTokenUtil.getHeaderMap());
            } else {
                InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
                resultStr = infExchangeService.exchange(new JSONObject(param));
            }
        } catch (Exception e) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("资源预判接口异常，请核实接口服务是否可用[json_middlleplatform_resourcePrejudge_resourcePrejudge]");
        }
        if (KiteStringUtils.isEmpty(resultStr)) {
            ErrorConsts.INF_INVOKE_ERROR.throwOut(RES_PREJUDGE_API_OP_CODE, "资源预判接口", "核查失败");
        }
        Object resultObj;
        // 返回内容
        Map respMap = JSON.parseObject(resultStr, Map.class);
        Map uniBssBodyResult = MapUtils.getMap(respMap, "UNI_BSS_BODY");
        if (KiteMapUtils.isEmpty(uniBssBodyResult)) {
            resultObj = "调用核查接口返回数据为空！";
            return resultObj;
        }
        ResPrejudgeApiRspDTO resPrejudgeApiRsp = JSONObject.parseObject(JSON.toJSONString(uniBssBodyResult.get("RES_PREJUDGE_API_RSP")), ResPrejudgeApiRspDTO.class);

        if (Objects.nonNull(resPrejudgeApiRsp) && KiteStringUtils.isNotEmpty(resPrejudgeApiRsp.getRespCode())) {
            // 省份个性化条件不为空，返回String，其他返回List，默认是返回List
            if (KiteListUtils.isNotEmpty(resPrejudQryDTO.getAddressAttrInfo())) {
                resultObj = resPrejudgeApiRsp.getRespCode() + "——" +resPrejudgeApiRsp.getRespDesc();
            } else {
                if (KiteListUtils.isEmpty(resPrejudgeApiRsp.getAccessList())) {
                    ErrorConsts.BUSI_COMMON_ERROR.throwOut(resPrejudgeApiRsp.getRespDesc());
                }
                resultObj = this.formResPonseMessage(resPrejudgeApiRsp.getAccessList(), resPrejudgeApiRsp.getRespCode());
            }
        } else {
            if (KiteListUtils.isNotEmpty(resPrejudQryDTO.getAddressAttrInfo())) {
                resultObj = "";
            } else {
                resultObj = new ArrayList<>();
            }
        }
        return resultObj;
    }

    /**
     * 组装请求报文
     */
    private ResPrejudQryDTO formRequestMessages(ResPreQryDTO resPreQryDTO) {
        ResPrejudQryDTO resPrejudQryDTO = new ResPrejudQryDTO();
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        UserInfo userInfo = ContextUtil.getLoginInfo().getUserInfo();
        ContextUtil.getLoginInfo().getPostInfos();

        String staffId = KiteMapUtils.getString(userInfo.getExtParams(), "accountId"); // 集客工号
        //请求报文
        RoutingDTO routingDTO = new RoutingDTO();
        routingDTO.setRouteType("00");
        routingDTO.setRouteValue("04");
        resPrejudQryDTO.setRouting(routingDTO);
        resPrejudQryDTO.setOperId(staffId);
        resPrejudQryDTO.setProvinceCode(resPreQryDTO.getProvinceCode());
        resPrejudQryDTO.setCityCode(resPreQryDTO.getCityCode());
        resPrejudQryDTO.setEparchyCode(resPreQryDTO.getEparchyCode());
        resPrejudQryDTO.setChannelId(getDepartId());
        resPrejudQryDTO.setChannelType("9999999");
        resPrejudQryDTO.setAntiType("0");
        resPrejudQryDTO.setExchCode("");
        resPrejudQryDTO.setAddressCode(resPreQryDTO.getAddressCode());
        String sceneInstId = resPreQryDTO.getSceneInstId();
        KiteOfferInst mainOfferInst = querySceneInstService.getMainOfferInst(sceneInstId);
        List<OfferDetail> offerDetails = OfferCache.get(mainOfferInst.getOfferId()).listAccessProdDetail();
        if (KiteListUtils.isNotEmpty(offerDetails)) {
            resPrejudQryDTO.setServiceId(offerDetails.get(0).getRoleId());
            resPrejudQryDTO.setProductId(offerDetails.get(0).getObjId());
        }
        // 处理省份个性化查询条件
        this.dealCondition(resPrejudQryDTO, resPreQryDTO, mainOfferInst.getOfferId());
        return resPrejudQryDTO;
    }

    private List<AccessFrontDTO> formResPonseMessage(List<AccessDTO> accessList, String respCode) {
        List<AccessFrontDTO> accessFrontDTOS = KiteCartBeanUtils.copyPropsForList(accessList, AccessFrontDTO.class);
        KiteBeanUtils.transform(accessList, AccessFrontDTO.class);
        for (int i = 0; i < accessList.size(); i++) {
            AccessFrontDTO accessFront = accessFrontDTOS.get(i);
            AccessDTO access = accessList.get(i);
            List<ExchDTO> exchDTOList = access.getExchList();
            accessFront.setPrejudgeRes("存在可用资源");
            if (KiteListUtils.isNotEmpty(exchDTOList)) {
                accessFront.setExchName(exchDTOList.get(0).getExchName());
            }
            List<AddrAttrInfoDTO> addrAttrInfoDTOList = access.getAddressAttrInfo();
            if (KiteListUtils.isNotEmpty(addrAttrInfoDTOList)) {
                List<AddrAttrInfoDTO> ponTypeL = addrAttrInfoDTOList.stream().filter(addrAttrInfoDTO -> KiteStringUtils.equals("10002214", addrAttrInfoDTO.getAttrCode())).collect(Collectors.toList());
                List<AddrAttrInfoDTO> manufacturerL = addrAttrInfoDTOList.stream().filter(addrAttrInfoDTO -> KiteStringUtils.equals("10002215", addrAttrInfoDTO.getAttrCode())).collect(Collectors.toList());
                List<AddrAttrInfoDTO> isInteroperL = addrAttrInfoDTOList.stream().filter(addrAttrInfoDTO -> KiteStringUtils.equals("10002216", addrAttrInfoDTO.getAttrCode())).collect(Collectors.toList());
                accessFront.setListNbr(KiteStringUtils.valueOf(i));
                accessFront.setRespCode(respCode);
                if (KiteListUtils.isNotEmpty(ponTypeL)) {
                    accessFront.setPonType(ponTypeL.get(0).getAttrValueName());
                }
                if (KiteListUtils.isNotEmpty(manufacturerL)) {
                    accessFront.setManufacturer(manufacturerL.get(0).getAttrValueName());
                }
                if (KiteListUtils.isNotEmpty(isInteroperL)) {
                    accessFront.setIsInteroper(isInteroperL.get(0).getAttrValueName());
                }
            }
        }
        return accessFrontDTOS;
    }

    private static String getDepartId() {
        Long departId = 0L;
        List<PostInfo> postInfos = ContextUtil.getLoginInfo().getPostInfos();
        if (KiteListUtils.isNotEmpty(postInfos)) {
            departId = Optional.ofNullable(postInfos.get(0)).map(PostInfo::getPostId).orElse(0L);
        }
        return String.valueOf(departId);
    }

    /**
     * 处理省份个性化查询条件
     * @param resPrejudQryDTO
     * @param resPreQryDTO
     */
    private void dealCondition(ResPrejudQryDTO resPrejudQryDTO, ResPreQryDTO resPreQryDTO, String goodSku) {
        Map<String, Object> conditions = resPreQryDTO.getCondition();
        if (Objects.isNull(conditions) || conditions.isEmpty()) {
            return;
        }
        List<MappingGoodsVO> mappingGoodsVOList = new ArrayList<>();
        MappingGoodsVO mappingGoodsVO = new MappingGoodsVO();
        mappingGoodsVO.setProductSku(goodSku);
        mappingGoodsVO.setConvertType("2"); // 1 集客转产商品 2 产商品转集客
        mappingGoodsVOList.add(mappingGoodsVO);

        List<MappingProductVO> mappingProductVOList = new ArrayList<>();
        List<MappingAttrVO> mappingAttrVOList = new ArrayList<>();
        MappingProductVO mappingProductVO = new MappingProductVO();
        mappingProductVO.setProductId(resPrejudQryDTO.getProductId());
        mappingProductVO.setAttrs(mappingAttrVOList);
        mappingProductVOList.add(mappingProductVO);
        mappingGoodsVO.setProducts(mappingProductVOList);

        conditions.entrySet().stream().forEach(condition -> {
            MappingAttrVO mappingAttrVO = new MappingAttrVO();
            mappingAttrVO.setAttrcode(condition.getKey());
            mappingAttrVO.setAttrvalue(String.valueOf(condition.getValue()));
            if (!mappingAttrVOList.stream().anyMatch(attr -> KiteStringUtils.equals(attr.getAttrcode(), mappingAttrVO.getAttrcode()))) {
                mappingAttrVOList.add(mappingAttrVO);
            }
        });

        List<AddrAttrInfoDTO> addressAttrInfo = Optional.ofNullable(resPrejudQryDTO.getAddressAttrInfo()).orElse(new ArrayList<>());
        // 属性编码转换
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("goods", mappingGoodsVOList);
        List<MappingGoodsVO> resultMappingGoodsList = this.attrMappingService(paramMap);
        resultMappingGoodsList.forEach(resultMappingGoods -> {
            List<MappingProductVO> resultMappingProductList = resultMappingGoods.getProducts();
            if (KiteListUtils.isNotEmpty(resultMappingProductList)) {
                resultMappingProductList.forEach(resultMappingProduct -> {
                    List<MappingAttrVO> attrVOS = resultMappingProduct.getAttrs();
                    attrVOS.stream().forEach(attrVO -> {
                        if (!addressAttrInfo.stream().anyMatch(addr -> KiteStringUtils.equals(addr.getAttrCode(), attrVO.getDestAttrcode()))) {
                            AddrAttrInfoDTO addrAttrInfoDTO = new AddrAttrInfoDTO();
                            addrAttrInfoDTO.setAttrCode(attrVO.getDestAttrcode());
                            addrAttrInfoDTO.setAttrValue(attrVO.getDestAttrvalue());
                            addressAttrInfo.add(addrAttrInfoDTO);
                        }
                    });
                });
            }
        });
        resPrejudQryDTO.setAddressAttrInfo(addressAttrInfo);
    }

    @Override
    public List<MappingGoodsVO> attrMappingService(Map<String, Object> paramMap) {
        Map<String, Object> uniBssBody = new HashMap();
        uniBssBody.put("ATTRS_MAPPING_SERVICE_REQ", paramMap);
        Map<String, Object> reqParam = new HashMap<>();
        reqParam.put("UNI_BSS_BODY", uniBssBody);
        reqParam.put("OP_CODE", ATTR_MAPPING_API_OP_CODE);
        InfServiceHelper.adaptGray(reqParam, uniBssBody);
        String resultStr;
        if (KiteStringUtils.isEqual(mode, "http")) {
            resultStr = HttpsCallClient.postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, reqParam, LocalTokenUtil.getHeaderMap());
        } else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            resultStr = infExchangeService.exchange(new JSONObject(reqParam));
        }
        if (KiteStringUtils.isEmpty(resultStr)) {
            ErrorConsts.INF_INVOKE_ERROR.throwOut(ATTR_MAPPING_API_OP_CODE, "属性编码转换接口",
                "属性编码转换接口调用失败");
        }
        Map<String, Object> resultMap = JSONObject.parseObject(resultStr, Map.class);
        Map headMap = MapUtils.getMap(resultMap, "UNI_BSS_HEAD");
        if(!"00000".equals(MapUtils.getString(headMap, "RESP_CODE"))) {
            ErrorConsts.INF_INVOKE_ERROR.throwOut(ATTR_MAPPING_API_OP_CODE, "属性编码转换接口", "调用属性编码转换接口失败,调用接口状态编码为：" + MapUtils.getString(headMap, "RESP_DESC"));
        }
        Map respBody = MapUtils.getMap(resultMap, "UNI_BSS_BODY");
        Map<String, Object> attrsMappingServiceRsp = KiteMapUtils.getMap(respBody, "ATTRS_MAPPING_SERVICE_RSP");
        String status = KiteMapUtils.getString(attrsMappingServiceRsp, "status");
        String message = KiteMapUtils.getString(attrsMappingServiceRsp, "message");
        if (!"0".equals(status)) {
            ErrorConsts.INF_INVOKE_ERROR.throwOut(ATTR_MAPPING_API_OP_CODE, "属性编码转换接口", "调用属性编码转换接口失败: " + message);
        }
        List<MappingGoodsVO> mappingGoodsVOList = new ArrayList<>();
        Map<String, Object> goodsMap = KiteMapUtils.getMap(attrsMappingServiceRsp, "data");
        List<Map<String, Object>> goodsList = (List<Map<String, Object>>) goodsMap.get("goods");
        for (Map<String, Object> goods : goodsList) {
            mappingGoodsVOList.add(JSONObject.parseObject(JSON.toJSONString(goods), MappingGoodsVO.class));
        }
        return mappingGoodsVOList;
    }
}
